package by.ad.servlet;

import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import by.ad.xml.XmlUtils;
import static by.ad.HttpUtils.CONTENT_TYPE;
import static by.ad.HttpUtils.TEXT_HTML;
import static by.ad.HttpUtils.X_FRAME_OPTIONS;
import static com.google.common.base.Charsets.UTF_8;

@SuppressWarnings("serial")
public class RawResourceServlet
  extends HttpServlet
{
  /*@Override
  public long getLastModified(final HttpServletRequest req) 
  {
    return ((CachedPage) req.getAttribute(CACHED_PAGE)).lastModified.getTime();
  }*/
  
  @Override
  public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
    throws IOException, ServletException
  {
    resp.setCharacterEncoding(UTF_8.name());
    resp.setStatus(200);
    
    final String configContentType = getServletConfig().getInitParameter(CONTENT_TYPE);
    final String defaultContentType = configContentType != null ? configContentType : TEXT_HTML;  
    resp.setContentType(defaultContentType);
    
    final String configXFrameOptions = getServletConfig().getInitParameter(X_FRAME_OPTIONS);
    if (configXFrameOptions != null)
      resp.setHeader(X_FRAME_OPTIONS, configXFrameOptions);
    
    final ServletOutputStream out = resp.getOutputStream();
    try {
      final InputStream data = XmlUtils.getInputSource(req.getRequestURI()).getByteStream();
      ByteStreams.copy(data, out);
    } catch (URISyntaxException e) {
      throw new IOException(e);
    }
  }
  
}
